import sys
import re

filepath = sys.argv[1]
dictpath = sys.argv[2]

idict = {}
text = ""

def readfile(filename):
    try:
        try:
            try:
                with open(filename,'r',encoding='utf-8') as r:
                    lines=r.readlines()
            except:
                with open(filename, 'r', encoding='gbk') as r:
                    lines = r.readlines()
        except:
            with open(filename, 'r', encoding='utf-16') as r:
                lines = r.readlines()
    except:
        with open(filename, 'r', encoding='GB2312') as r:
            lines = r.readlines()
    return lines


dict = readfile(dictpath)
for i in dict:
    word = i.split("\t")
    num = word[0]
    idict[word[0].strip()] = word[1].strip()


f = readfile(filepath)
for i in range(0,len(f),2):
    num = f[i].split("\t")[0]

    words = f[i].split("\t")[1].strip("%.\n").split(" ")
    yins = f[i+1].split("\t")[1].strip().split("/")
    wordline = ""
    yinline = ""
    try:
        for j in range(len(words)):
            if words[j] in idict.keys():
                if yins[j].strip() == idict[words[j]]:
                    wordline = wordline+words[j]+" "
                    yinline = yinline+yins[j]+"/"
                else:
                    wordline = wordline + "*"+words[j] + " "
                    yinline = yinline + " " +idict[words[j]] + " /"
            else:
                wordline = wordline + words[j] + " "
                yinline = yinline + yins[j] + "/"
        if re.search('%[^%]*$',f[i].rstrip('\n')):
            end_baifenhao=re.search('%[^%]*$',f[i].rstrip('\n')).group()
        else:
            end_baifenhao=''
        text = text+num+"\t"+wordline.strip()+end_baifenhao+"\n"
        text = text+"\t"+yinline.strip("/")+"\n"

        '''            print(num)
        print(wordline.strip()+"%.")
        print(yinline.strip("/"))'''

    except Exception:
        text = text+num+"\n"+"该句存在格式错误"+"\n"
        #print(num,"该句存在格式错误")

with open("意大利语词典替换输出文本.txt","w",encoding="utf-8") as w:
    w.write(text)
